﻿using LogisticsTrackingWebApi_V3.Models;
using LogisticsTrackingWebApi_V3.Services;

namespace LogisticsTrackingWebApi_V3.ServicesImpl
{

    /// <summary>
    /// 物流查询服务实现
    /// </summary>
    public class LogisticsService : ILogisticsService
    {
        private readonly LogisticsProviderFactory _providerFactory;

        public LogisticsService(LogisticsProviderFactory providerFactory)
        {
            _providerFactory = providerFactory;
        }

        public IEnumerable<LogisticsCompany> GetSupportedCompanies()
        {
            return _providerFactory.GetSupportedCompanies();
        }

        public async Task<LogisticsInfo> QueryLogisticsAsync(string trackingNumber, string? companyCode = null)
        {
            if (string.IsNullOrWhiteSpace(trackingNumber))
                throw new ArgumentException("运单号不能为空");

            // 获取合适的物流查询提供者
            ILogisticsProvider provider;
            if (!string.IsNullOrEmpty(companyCode))
            {
                provider = _providerFactory.GetProvider(companyCode);
            }
            else
            {
                // 自动猜测物流公司
                provider = _providerFactory.GuessProvider(trackingNumber)
                           ?? throw new InvalidOperationException("无法识别运单号对应的物流公司，请指定公司代码");
            }

            // 调用查询
            return await provider.QueryTrackingAsync(trackingNumber);
        }
    }

}
